// 嵌入的proto文件内容
const protoDefinition = `
syntax = "proto3";

package fishshoot;

message Fishshoot {
  int32 fishId = 1;
  string userToken = 2;
  int32 bullet = 3;
  int32 healthPoint = 4;
  string messageType = 5;
  int32 gold = 6;
  int32 roomId = 7;
}
`
// 解析proto文件
const root = protobuf.parse(protoDefinition).root
const Fishshoot = root.lookupType('fishshoot.Fishshoot')

// 获取url中的参数
const urlParams = new URLSearchParams(window.location.search)
const roomId = urlParams.get('roomId')

// 创建websocket连接
const socket = new WebSocket('ws://localhost:7000/ws')
socket.binaryType = 'arraybuffer'
socket.onopen = () => {
    console.log('WebSocket连接已打开')

    // 初始化鱼
    sendMessage('initFish')
}
socket.onmessage = function (event) {
    const uint8Array = new Uint8Array(event.data)
    const message = Fishshoot.decode(uint8Array)

    console.log('Received message:', message)

    let messageType = message.messageType
    if (messageType === 'initFish') {
        document.getElementById('healthPoint').innerHTML = message.healthPoint
        document.getElementById('gold').innerHTML = message.gold
    } else if (messageType === 'shoot') {
        document.getElementById('healthPoint').innerHTML = message.healthPoint
        document.getElementById('gold').innerHTML = message.gold
    }
}

function shoot(bullet) {
    if (document.getElementById('healthPoint').innerHTML <= 0 || parseInt(document.getElementById('gold').innerHTML) <= 0) {
        alert('游戏结束')
        return
    }
    const messageInput = {
        fishId: 1,
        messageType: 'shoot',
        bullet: bullet,
        userToken: '1',
        roomId: roomId
    }

    console.log('Sending message:', messageInput)

    const message = Fishshoot.create(messageInput)
    const buffer = Fishshoot.encode(message).finish()
    socket.send(buffer)
}

function sendMessage(messageType, fishId) {
    const messageInput = {
        fishId: fishId,
        messageType: messageType,
        userToken: '1',
        roomId: roomId
    }

    console.log('Sending message:', messageInput)

    const message = Fishshoot.create(messageInput)
    const buffer = Fishshoot.encode(message).finish()
    socket.send(buffer)
    // document.getElementById('messageInput').value = ''
}

socket.onclose = (event) => {
    console.log('WebSocket连接已关闭:', event)
}
socket.onerror = (error) => {
    console.error('WebSocket连接发生错误:', error)
}
// 将sendMessage函数绑定到全局对象
window.sendMessage = sendMessage